#include "stdafx.h"
#include "net/HTTPBasicCredentials.hpp"
#include "stdlib/exception.hpp"
using JHCPP::stdlib::jhException::NotAuthenticatedException;
#include "stream/base64decode.hpp"
#include "stream/base64encode.hpp"
using JHCPP::stream::CBase64Decode;
using JHCPP::stream::CBase64Encode;
#include <sstream>

NET_NAMESPACE_BEGIN

const std::string CHTTPBasicCredentials::SCHEME = "Basic";

CHTTPBasicCredentials::CHTTPBasicCredentials()
{
}

CHTTPBasicCredentials::CHTTPBasicCredentials(const std::string& username, const std::string& password)
	: m_username(username),
	m_password(password)
{
}

CHTTPBasicCredentials::CHTTPBasicCredentials(const CHTTPRequest& request)
{
	std::string scheme;
	std::string authInfo;
	request.getCredentials(scheme, authInfo);
	if (icompare(scheme, SCHEME) == 0)
	{
		parseAuthInfo(authInfo);
	}
	else 
		throw NotAuthenticatedException("Basic authentication expected");
}

CHTTPBasicCredentials::CHTTPBasicCredentials(const std::string& authInfo)
{
	parseAuthInfo(authInfo);
}

CHTTPBasicCredentials::~CHTTPBasicCredentials()
{
}

void CHTTPBasicCredentials::setUsername(const std::string& username)
{
	m_username = username;
}

const std::string& CHTTPBasicCredentials::getUsername() const
{
	return m_username;
}

void CHTTPBasicCredentials::setPassword(const std::string& password)
{
	m_password = password;
}

const std::string& CHTTPBasicCredentials::getPassword() const
{
	return m_password;
}

void CHTTPBasicCredentials::authenticate(CHTTPRequest& request) const
{
	std::ostringstream ostr;
	CBase64Encode encoder(ostr);
	encoder.rdbuf()->setLineLength(0);
	encoder << m_username << ":" << m_password;
	encoder.close();
	request.setCredentials(SCHEME, ostr.str());
}

void CHTTPBasicCredentials::proxyAuthenticate(CHTTPRequest& request) const
{
	std::ostringstream ostr;
	CBase64Encode encoder(ostr);
	encoder.rdbuf()->setLineLength(0);
	encoder << m_username << ":" << m_password;
	encoder.close();
	request.setProxyCredentials(SCHEME, ostr.str());
}

void CHTTPBasicCredentials::parseAuthInfo(const std::string& authInfo)
{
	static const int eof = std::char_traits<char>::eof();

	std::istringstream istr(authInfo);
	CBase64Decode decoder(istr);
	int ch = decoder.get();
	while (ch != eof && ch != ':')
	{
		m_username += (char) ch;
		ch = decoder.get();
	}
	if (ch == ':') ch = decoder.get();
	while (ch != eof)
	{
		m_password += (char) ch;
		ch = decoder.get();
	}
}

NET_NAMESPACE_END
